package cn.it.shop.util;

import java.io.File;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.it.shop.model.FileImage;

/**
 * @author zsl
 * 
 */

@Component("fileUpload")
public class FileUploadUtil implements FileUpload {
	private String	filePath	= "C:\\";

	// 通过文件名，获取扩展名
	@Value("#{prop.filePath}")
	public void setFilePath(String filePath) {
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
				+ filePath);
		this.filePath = filePath;
	}

	private String getExtName(String filename) {
		return FilenameUtils.getExtension(filename);
	}

	// 使用UUID自动生成文件名
	private String newFilename(String filename) {
		return UUID.randomUUID().toString() + "." + getExtName(filename);
	}

	// 实现文件上传功能，返回新的文件名称

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.it.shop.util.FileUpload#uploadFile(cn.it.shop.model.FileImage)
	 */
	@Override
	public String uploadFile(FileImage fileImage) {
		String pic = newFilename(fileImage.getFilename());
		try {
			FileUtil.copyFile(fileImage.getFile(), new File(filePath, pic));
			return pic;
		} catch (Exception e) {
			throw new RuntimeException();
		} finally {
			fileImage.getFile().delete();
		}
	}
}
